package com.glsc.ngateway.flowable.service;

import cn.hutool.core.collection.CollectionUtil;
import com.glsc.ngateway.common.api.flowable.dto.ParamEmailDto;
import com.glsc.ngateway.common.base.domain.mysql.gateway.other.EmailClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author zhouzp
 * @date 2020/6/17
 * 邮件发送服务
 */
@Service
public class MailService {

    private static Logger logger = LoggerFactory.getLogger(MailService.class);

    @Value("${spring.mail.username}")
    public String gatewayMail;

    @Resource(name = "mailSender")
    private JavaMailSender mailSender;

    /*检查发件信息是否合法*/
    protected void checkEmailValid(String sender, String recipient, String title) {
        if (sender == null || sender.isEmpty()) {
            throw new RuntimeException("发件人不能为空");
        }
        if (recipient == null || recipient.isEmpty()) {
            throw new RuntimeException("收件人不能为空");
        }
        if (title == null || title.isEmpty()) {
            throw new RuntimeException("邮件标题不能为空");
        }
    }

    /**
     * @param 发送需求管理通知邮件
     */
    public void sendEmail(ParamEmailDto dto) throws Exception {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
            String sender = dto.getSender();
            if (StringUtils.isEmpty(sender)) {
                sender = gatewayMail;
            }
            String recipients = dto.getRecipient();
            String randomStr = UUID.randomUUID().toString();
            String title = dto.getTitle();
            checkEmailValid(sender, recipients, title);
            helper.setFrom(sender);
            Set<String> recivers = Arrays.asList(recipients.split(",")).stream()
                    .map(reciver -> reciver.trim())
                    .filter(reciver -> !reciver.isEmpty())
                    .collect(Collectors.toSet());
            String[] to = new String[recivers.size()];
            helper.setTo(recivers.toArray(to));
            helper.setSubject(title);
            String context = dto.getContext();
            helper.setText(context, true);//邮件内容
            if (CollectionUtil.isNotEmpty(dto.getAttachmentList())){
                buildAttachmentList(dto.getAttachmentList(),helper,null);
            }
            mailSender.send(message);
        } catch (Exception e) {
            logger.error("邮件服务初始化失败message：" + e.getMessage(), e);
            logger.error("收件邮箱：" + dto.getRecipient() + "， 邮件标题： " + dto.getTitle() + "， 邮件内容：" + dto.getContext() + "");
        }
    }

    /**
     * 处理邮件附件单独出来可以复用
     *
     * @param attachmentList
     * @param helper
     * @param ec
     * @throws MessagingException
     */
    private void buildAttachmentList(List<File> attachmentList, MimeMessageHelper helper, EmailClient ec) throws MessagingException, UnsupportedEncodingException {
        //保存文件内容需要保存文件路径列表和文件名称列表供重新发送使用
        StringBuilder filePathListApp = new StringBuilder("");
        StringBuilder fileNameListApp = new StringBuilder("");
        String fileNameList = null;
        String filePathList = null;
        if (!CollectionUtils.isEmpty(attachmentList)) {//附件不为空
            for (File attachment : attachmentList) {
                helper.addAttachment(MimeUtility.encodeWord(attachment.getName(), "UTF-8", "B"), attachment);
                filePathListApp.append(attachment.getAbsolutePath()).append(",");
                fileNameListApp.append(attachment.getName()).append(",");
            }
            filePathList = filePathListApp.toString();
            fileNameList = fileNameListApp.toString();
            filePathList = filePathList.substring(0, filePathList.length() - 1);
            fileNameList = fileNameList.substring(0, fileNameList.length() - 1);
//            ec.setFilePathList(filePathList);
//            ec.setFileNameList(fileNameList);
        }
    }
}

